package cn.example.vip.mall.cart.controller;

import cn.example.vip.mall.cart.entity.Cart;
import cn.example.vip.mall.cart.service.CartService;
import cn.example.vip.mall.util.RespResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/cart")
public class CartController {
	@Autowired
	private CartService cartService;
	@Autowired
	private HttpServletRequest request;
	
	/**
	 * 商品添加到购物车
	 * @param id 商品id
	 * @param num 商品数量
	 * @return
	 */
	@GetMapping("/{id}/{num}")
	public RespResult addCart(@PathVariable("id") String id,
							  @PathVariable("num")Integer num) {
		// 从过滤过的请求头获取用户名
		String userName = request.getHeader("username");	//"test";
		cartService.add(id, userName, num);
		// 服务端设置响应头
//		response.setHeader("Content-Type", "application/json");
		return RespResult.ok();
	}
	
	/**
	 * 查询用户购物车列表
	 * @return
	 */
	@GetMapping("/list")
	public RespResult<List<Cart>> queryCartList() {
		String userName = "test";
		return RespResult.ok(cartService.list(userName));
	}
	
	/**
	 * 查询购物车,用户选中的商品
	 */
	@PostMapping("/list")
	RespResult<List<Cart>> queryCarts(@RequestBody List<String> ids){
		String userName = "test";
		List<Cart> carts = cartService.queryCartsByIds(ids);
		return RespResult.ok(carts);
	}
	
	/**
	 * 删除用户选中并购买的商品
	 */
	@DeleteMapping
	RespResult<List<Cart>> delCarts(@RequestBody List<String> ids){
		String userName = "test";
		cartService.delete(ids);
		return RespResult.ok();
	}
}
